<template>
  <div>
    <h2>排产计划管理</h2>
    
    <!-- 操作区域 -->
    <div class="action-bar">
      <el-button type="primary" @click="loadPlans" :loading="loading">
        <el-icon><Refresh /></el-icon>
        刷新列表
      </el-button>
      <el-button type="success" @click="$emit('execute-plan')">
        新建排产计划
      </el-button>
    </div>
    
    <!-- 排产计划列表 -->
    <el-table 
      :data="plans" 
      style="width: 100%" 
      v-loading="loading"
      border
      stripe
    >
      <el-table-column prop="planId" label="计划ID" width="180" show-overflow-tooltip sortable />
      <el-table-column prop="planName" label="计划名称" width="200" show-overflow-tooltip sortable />
      <el-table-column prop="algorithmType" label="算法类型" width="180" sortable>
        <template #default="scope">
          {{ getAlgorithmDisplayName(scope.row.algorithmType) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" sortable>
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="planStartTime" label="计划开始时间" width="160" sortable />
      <el-table-column prop="planEndTime" label="计划结束时间" width="160" sortable />
      <el-table-column prop="totalUtilization" label="设备利用率" width="120" sortable>
        <template #default="scope">
          {{ scope.row.totalUtilization ? (scope.row.totalUtilization ).toFixed(1) + '%' : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="createdBy" label="创建人" width="100" sortable />
      <el-table-column prop="createTime" label="创建时间" width="160" sortable />
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="viewDetails(scope.row)">详情</el-button>
          <el-button 
            size="small" 
            type="warning" 
            @click="confirmPlan(scope.row)"
            :disabled="scope.row.status !== '草稿'"
          >
            确认
          </el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="deletePlan(scope.row)"
            :disabled="scope.row.status === '执行中'"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Refresh } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

const API_BASE_URL = 'http://117.72.45.141:8091';
const router = useRouter();

// 定义事件发射器
const emit = defineEmits(['execute-plan']);

// 响应式数据
const plans = ref([]);
const loading = ref(false);

// 算法名称映射
const algorithmNameMap = {
  'PRODUCT_BATCH': '同种产品集中生产算法', 
  'MACHINE_UTILIZATION': '负载均衡算法',
  'ENHANCED_GENETIC_ALGORITHM': '增强遗传算法',
  'DEFAULT_FIFO': 'FIFO默认排序算法',
  'CRITICAL_PATH_SPT': '关键路径SPT算法',
  'COMBINE_ALGORITHM': '紧急优先与机器利用率结合算法',
  'TEST_ALGORITHM': '测试算法'
};

// 加载排产计划列表
const loadPlans = async () => {
  loading.value = true;
  try {
    const response = await axios.get(`${API_BASE_URL}/api/schedule/plans`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      plans.value = response.data.data || [];
      ElMessage.success(`成功加载 ${plans.value.length} 个排产计划`);
    } else {
      ElMessage.error(response.data.message || '加载排产计划失败');
    }
  } catch (error) {
    console.error('加载排产计划失败:', error);
    ElMessage.error('加载排产计划失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

// 查看排产计划详情 - 跳转到独立页面
const viewDetails = (plan) => {
  console.log('查看计划详情:', plan);
  router.push(`/schedule-plan/${plan.planId}`);
};

// 确认排产计划
const confirmPlan = async (plan) => {
  try {
    await ElMessageBox.confirm(
      `确定要确认排产计划 "${plan.planName}" 吗？确认后将开始执行该计划。`,
      '确认排产计划',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const response = await axios.put(`${API_BASE_URL}/api/schedule/confirm/${plan.planId}`, null, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      ElMessage.success('排产计划确认成功');
      loadPlans();
    } else {
      ElMessage.error(response.data.message || '确认失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认排产计划失败:', error);
      ElMessage.error('确认失败，请检查网络连接');
    }
  }
};

// 删除排产计划
const deletePlan = async (plan) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除排产计划 "${plan.planName}" 吗？此操作不可逆。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const response = await axios.delete(`${API_BASE_URL}/api/schedule/plans/${plan.planId}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      ElMessage.success('排产计划删除成功');
      loadPlans();
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除排产计划失败:', error);
      ElMessage.error('删除失败，请检查网络连接');
    }
  }
};

// 状态标签类型
const getStatusTagType = (status) => {
  const types = {
    '草稿': 'info',
    '已确认': 'success',
    '执行中': 'warning',
    '已完成': 'primary'
  };
  return types[status] || 'default';
};

// 算法显示名称
const getAlgorithmDisplayName = (algorithmType) => {
  return algorithmNameMap[algorithmType] || algorithmType;
};

onMounted(() => {
  loadPlans();
});

// 暴露方法给父组件
defineExpose({
  loadPlans
});
</script>

<style scoped>
.action-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

h3 {
  margin: 20px 0 10px 0;
  color: #409eff;
  font-weight: 600;
}
</style> 